package com.example.mystore.service.impl;

import com.example.mystore.mapper.UserProductCategoryMapper;
import com.example.mystore.model.ProductCategory;
import com.example.mystore.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserProductCategoryService {

    @Autowired
    private UserProductCategoryMapper userProductCategoryMapper;




    public List<ProductCategory> getSpecificCategories() {
        return userProductCategoryMapper.getSpecificCategories();
    }



    public List<ProductCategory> getAllCategories() {
        List<ProductCategory> allCategories = userProductCategoryMapper.findAllCategories();
        return buildCategoryTree(allCategories);
    }
    public List<Product> getProductsByTypeId(int typeId) {
        return userProductCategoryMapper.findProductsByTypeId(typeId);}

    private List<ProductCategory> buildCategoryTree(List<ProductCategory> categories) {
        // 按照 level 和 sort_order 排序
        categories.sort(Comparator.comparingInt(ProductCategory::getLevel).thenComparingInt(ProductCategory::getSortOrder));

        // 将分类按照 parent_id 分组
        Map<Integer, List<ProductCategory>> groupedByParentId = categories.stream()
                .collect(Collectors.groupingBy(ProductCategory::getParentId));

        // 构建分类树
        categories.forEach(category -> category.setChildren(groupedByParentId.get(category.getId())));

        // 返回顶级分类（level = 0，parent_id = 0）
        return groupedByParentId.get(0);
    }
}
